/*
 *                                                     __----~~~~~~~~~~~------___
 *                                    .  .   ~~//====......          __--~ ~~
 *                    -.            \_|//     |||\\  ~~~~~~::::... /~
 *                 ___-==_       _-~o~  \/    |||  \\            _/~~-
 *         __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
 *     _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
 *   .~       .~       |   \\ -_    /  /-   /   ||      \   /
 *  /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
 *  |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
 *           '         ~-|      /|    |-~\~~       __--~~
 *                       |-~~-_/ |    |   ~\_   _-~            /\
 *                            /  \     \__   \/~                \__
 *                        _--~ _/ | .-~~____--~-/                  ~~==.
 *                       ((->/~   '.|||' -_|    ~~-/ ,              . _||
 *                                  -_     ~\      ~~---l__i__i__i--~~_/
 *                                  _-~-__   ~)  \--______________--~~
 *                                //.-~~~-~_--~- |-------~~~~~~~~
 *                                       //.-~~~--\
 *                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 *                               神兽保佑            永无BUG
 *
 * @Author: pengzhiwen
 * @LastEditors: pengzhiwen
 * @Description: 
 * //自制的表格列表，方便修改样式，用那些组件改样式太麻烦了
//使用规则
//传入tableHeader和data、isOperate三个参数
//tableHeader格式：
// [
//     {
//         key: "xxx",  //data中该顺序位置对应的字段名
//         name: "xxx" //该顺序位置对应的表头名称
//         width: "xxx" //该字段所占的宽度，该功能不完善，最好自己计算所有宽度总和为100%否则可能会有问题,
//         title: "xxx" //该项悬浮出现的文字，不设置默认出现该值,
//         tdStyle: {} //单元格样式
//         trStyle: {} //行样式
//         pageSize: number //分页器一页大小
//         style: {} //表格样式
//     },
//     {
//         key: "xxx",
//         name: "xxx"
//     }
//     ...
// ]
//data格式：
//传入参数必须是数组，并且必须拥有与tableHeader内key值相同的所有字段，便于取值放于相应位置
//关于头像需要自己写地址参数，后续需要在tableHeader里添加一个头像对象，暂定为key: userHeader吧！
//isOperate用于是否添加编辑删除功能
 */
import React, {
    useState,
    useEffect
} from "react";
import table from "../table";
import { Pagination, ConfigProvider, message } from "antd";
import zhCN from "antd/es/locale/zh_CN";
import { Empty, Alert } from "../common";
import $ from "jquery";
import "./index.scss";

const RegTypeInfo = {
    "number": /^[0-9.]*$/g,   //纯数字(小数也可)
    "boolean": /^["是"|"否"]$/g,  //是or否
    "sick": /^["事假"|""]$/g,  //事假or病假
    "date": /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/g,  //日期xxxx-xx-xx
    "date-time": /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/g, //yyyy-mm-dd hh:mm:ss
}
function Table(props) {
    let {
        tableHeader,
        data,
        style,
        pageSize,
        trStyle,
        tdStyle,
        isOperate,
        haveChild,
        showChildInfo,
        updateFun
    } = props;
    const [currentIndex, setCurrentIndex] = useState(1);
    const [currentEditItem, setCurrentEditItem] = useState({});
    const [editData, setEditData] = useState({});
    const [alertVisible, setAlertVisible] = useState(false);
    //若数据有更新，则返回第一页
    useEffect(() => {
        setCurrentIndex(1);
    }, [data])
    //不是数组就不收，哪来的回哪去吧
    if(!Array.isArray(tableHeader) || !Array.isArray(data)){
        return;
    }
    const operateItem = (type, value) => {
        if(type === "edit"){
            setCurrentEditItem(value);
            setEditData(value);
        }
        if(type === "delete"){
            setEditData(value);
            setAlertVisible(true);
        }
        if(type === "confirm"){
            let value = editData;
            let sign = true;
            tableHeader.forEach((item, index)=>{
                let reg = item.type && new RegExp(RegTypeInfo[item.type]);
                let status = value[item.key];
                if(reg && !reg.test(status)){
                    message.config({
                        rtl: false,
                        getContainer: ()=>$(".data-table")[0]
                    });
                    message.warn(`${item.name}输入数据格式不正确，请重新输入`);
                    sign = false;
                } else if(item.maxLength && status.length > item.maxLength){
                    message.config({
                        rtl: false,
                        getContainer: ()=>$(".data-table")[0]
                    });
                    message.warn(`${item.name}输入数据请确保长度在${item.maxLength}位以内`);
                    sign = false;
                }
            })
            if(!sign){
                setTimeout(() => {
                    message.destroy();
                }, 2000);
                return;
            }
            typeof updateFun === "function" && updateFun(value, "edit");
            setCurrentEditItem({});
        }
        if(type === "cancel"){
            setCurrentEditItem({});
        }
        
    }
    //修改某一项数据对应的值,并保存起来
    const changeItem = (info, allData, e) => {
        let value = e.target.value;
        let myAllData = Object.assign({}, editData);
        myAllData[info.key] = value;
        setEditData(myAllData);
    }
    pageSize = pageSize? pageSize: 8;
    //若没有设置width值则默认都一样宽度
    let count = tableHeader.length;
    let width = parseInt(100/count) + "%";
    let updateDataList = [];

    //特殊设置，若值没有数据则不显示
    data.forEach((item)=>{
        let sign = true;
        tableHeader.forEach((child)=>{
            if(child.key == "score" && !item[child.key]){
                sign = false;
            }
            if(child.key == "useTime" && !item[child.key]){
                sign = false;
            }
        })
        if(sign){
            updateDataList.push(item);
        }
    })
    // console.log(updateDataList, "列表")
    return (
        <div className="data-table" style={style? style: null}>
            <div className="table-thead">
            {
                tableHeader.map((item, index)=>{
                    return (
                        <div
                        className="table-th" 
                        style={{
                            width,
                            textAlign: (item.name == "学生姓名" && tdStyle? tdStyle.textAlign: ""),
                            paddingLeft: (item.name == "学生姓名" && tdStyle? `calc( ${tdStyle.paddingLeft} + 30px )`: ""),
                        }}
                        key={index}
                        >{item.name}</div>
                    )
                })
            }
            </div>
            <div style={{minHeight: 480}}>
            {  
                Array.isArray(updateDataList) &&
                updateDataList.length > 0?
                updateDataList.slice((currentIndex - 1)*pageSize, currentIndex*pageSize).map((item, index)=>{
                    let arr = [];
                    tableHeader.forEach((child, index1)=>{
                        if(child.key === "index"){
                            arr.push(
                            <div 
                            className="table-td" 
                            style={{
                                width
                            }}
                            key={index1}>
                                {
                                    index + 1
                                }
                            </div>
                            )
                        } else if(child.key === "operate-btn"){
                            arr.push(
                                <div className="table-td" style={{
                                    width,
                                    display: (isOperate && currentEditItem.id && item.id === currentEditItem.id? "none": "inline-block")
                                }} key={index1}>
                                    <i className="editlogo" onClick={()=>operateItem("edit", item)}></i>
                                    <i className="deletelogo" onClick={()=>operateItem("delete", item)}></i>
                                </div>
                            )
                            if(isOperate){
                                arr.push(
                                    <div className="table-td" style={{
                                        width,
                                        display: (currentEditItem.id && item.id === currentEditItem.id? "inline-block": "none")
                                    }} key={"operate" + index1}>
                                        <i className="confirmlogo" onClick={()=>operateItem("confirm", item)}></i>
                                        <i className="cancellogo" onClick={()=>operateItem("cancel", item)}></i>
                                    </div>
                                )
                            }
                            
                        } else {
                            arr.push(
                            <div 
                            className="table-td" 
                            style={{
                                width,
                                display: (child.edit && isOperate && currentEditItem.id && item.id === currentEditItem.id? "none": "inline-block"),
                                textAlign: (child.key == "userName" && tdStyle? tdStyle.textAlign: ""),
                                paddingLeft: (child.key == "userName" && tdStyle? tdStyle.paddingLeft: ""),
                            }}
                            title={
                                child.title?
                                child.title:
                                typeof item[child.key] != "object"? 
                                item[child.key]: 
                                item[child.key]? 
                                "": 
                                "--"
                            }
                            key={index1}>
                                {
                                    child.key == "userName"?
                                    <img 
                                    className="user-head" 
                                    src={item.userImgUrl || item.studentImgUrl || item.photoPath}
                                    alt="" />:
                                    ""
                                }
                                {
                                    item[child.key]?
                                    typeof item[child.key] == "number"?
                                    child.originNumber?
                                    item[child.key]:
                                    item[child.key].toFixed(1):
                                    item[child.key]:
                                    "--"
                                }
                            </div>
                            )
                            if(isOperate){
                                arr.push(
                                    <div 
                                    className="table-input-container" 
                                    style={{
                                        width,
                                        display: (child.edit && currentEditItem.id && item.id === currentEditItem.id? "inline-block": "none")
                                    }}
                                    key={"input" + index1}>
                                        {
                                            child.edit && currentEditItem.id && item.id === currentEditItem.id?
                                            <input className="table-input" defaultValue={
                                                item[child.key]?
                                                typeof item[child.key] == "number"?
                                                child.originNumber?
                                                item[child.key]:
                                                item[child.key].toFixed(1):
                                                item[child.key]:
                                                ""
                                            } type="text" maxLength={20} onChange={(e)=>changeItem(child, item, e)}/>:
                                            ""
                                        }
                                        
                                    </div>
                                )
                            }
                            
                        } 
                    })
                    return (
                        <>
                        <div 
                        key={index}
                        className="table-tr" 
                        style={{
                            ...trStyle
                        }}>
                            {arr}
                        </div>
                        {/* {
                            haveChild && showChildInfo && showChildInfo.id === item.id?
                            Array.isArray(showChildInfo.list) &&
                            showChildInfo.list.length > 0?
                            showChildInfo.list.map((child, index2) => {
                                return (
                                    <div className="table-tr"key={index2}>
                                        <div className="table-td" style={{width}}>&nbsp;</div>
                                        <div className="table-td" style={{width}}>&nbsp;</div>
                                        <div className="table-td" style={{width}}>{child.result + child.unit}</div>
                                        <div className="table-td" style={{width}}>{child.score.toFixed(1)}</div>
                                    </div>
                                )
                            }):
                            <div className="table-tr">我是子列表</div>
                            :
                            ""
                        } */}
                        <div className="tr-slice-line" key={index+1}></div>
                        </>
                    )
                }):
                <Empty
                // className={"list-empty"}
                style={{margin: "183px 0"}}
                title={"暂无数据"}
                type={"4"}
                ></Empty>
            }
            </div>
            {
                updateDataList.length > pageSize?
                <ConfigProvider locale={zhCN}>
                    <Pagination
                    className="table-pagination"
                    size="small"
                    total={updateDataList.length}
                    current={currentIndex}
                    pageSize={pageSize}
                    showQuickJumper={false}
                    showSizeChanger={false}
                    hideOnSinglePage
                    onChange={(pageIndex)=>{
                        setCurrentIndex(pageIndex);
                    }}
                    />
                </ConfigProvider>
                :
                ""
            }
            <Alert
            type="btn-warn"
            show={alertVisible}
            title="是否确定删除该条记录？"
            onOk={()=>{
                setAlertVisible(false);
                typeof updateFun === "function" && updateFun(editData, "delete");
                setCurrentEditItem({});
                setEditData({});
            }}
            onCancel={()=>{
                setAlertVisible(false);
                setCurrentEditItem({});
                setEditData({});
            }}
            ></Alert>
        </div>  
    )
}

export default Table;